package mappers;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import utils.QuestionType;
import model.Answer;
import model.Question;
import dto.AnswerDTO;
import dto.QuestionDTO;

public class QuestionMapper {

	@PersistenceContext
	EntityManager em;

	public QuestionDTO mapDOMtoDTO(Question dom) {
		QuestionDTO dto = new QuestionDTO();

		dto.setId(dom.getId());
		dto.setText(dom.getText());
		dto.setType(dom.getType().name());
		List<AnswerDTO> answers = null;
		AnswerMapper answerMapper = new AnswerMapper();
		answers = new ArrayList<AnswerDTO>();
		for (Answer answer : dom.getAnswers()) {
			answers.add(answerMapper.mapDOMtoDTO(answer));
		}
		dto.setAnswers(answers);

		return dto;

	}

	public Question mapDTOtoDOM(QuestionDTO dto) {
		Question dom = null;

		if (dto.getId() == 0) {
			dom = new Question();
		} else {
			dom = em.find(Question.class, dto.getId());
		}
		
		dom.setText(dto.getText());
		dom.setType(getQuestionType(dto.getType()));
		List<Answer> answers = null;
		AnswerMapper answerMapper = new AnswerMapper();
		answers = new ArrayList<Answer>();

		for (AnswerDTO answer : dto.getAnswers()) {
			answers.add(answerMapper.mapDTOtoDOM(answer));
		}
		dom.setAnswers(answers);

		return dom;

	}
	
	private QuestionType getQuestionType(String name){
		return QuestionType.valueOf(name);		
		
	}

}
